package tvv.levelup.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Repository;
import tvv.levelup.models.Equipment;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by VLAD on 02.09.2014.
 */
@Repository
public class EquipmentDao implements IEquipmentDao {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public EquipmentDao(DriverManagerDataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public Equipment getEquipmentById(int id) {
        String query = "SELECT * FROM prt_db.equipment where id = ?";

        Equipment equipment = jdbcTemplate.queryForObject(query,
                new Object[]{new Integer(id)},
                new RowMapper<Equipment>() {
                    @Override
                    public Equipment mapRow(ResultSet resultSet, int i) throws SQLException {
                        Equipment eq = new Equipment();
                        eq.setId(resultSet.getInt("id"));
                        eq.setName(resultSet.getString("name"));
                        return eq;
                    }
                });
        return equipment;
    }

    @Override
    public void saveEquipment(Equipment eq) {
        String query = "INSERT INTO equipment (id, name) VALUES (?, ?)";
        jdbcTemplate.update(query, eq.getId(), eq.getName());
    }

    @Override
    public int getActualEquipmentId() {
        return jdbcTemplate.queryForInt("SELECT max(id) FROM prt_db.equipment") + 1;
    }
}

